﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Tobii.Gaming;


public class EyeTracker : MonoBehaviour
{
    private List<GazePoint> GazePoints = Serializer.GazePoints;
    private List<Vector3> GazePoints_v3;

    public void AppendGazePoint()
    {
#if DEVICE_CONNECTED
        GazePoint gp = TobiiAPI.GetGazePoint();
        if (gp.IsValid)
        {
            GazePoints.Add(gp);
        }
#else
        GazePoint gp = new GazePoint();
        GazePoints.Add(gp);
#endif

    }

#if false
    public float VisualizationDistance = 10f;
    public GameObject gazepoint;
    private Vector3 ProjectToPlaneInWorld(GazePoint gazePoint)
    {
        Vector3 gazeOnScreen = gazePoint.Screen;
        gazeOnScreen += (transform.forward * VisualizationDistance);

        return Camera.main.ScreenToWorldPoint(gazeOnScreen);
    }


    /*-------------------VISUALIZATION-----------------------------*/

    public void DrawPointCloud()
    {
        Debug.Log(GazePoints_v3.Count);

        var main = GetComponent<ParticleSystem>().main;
        main.startSpeed = 0.0f;                           // 设置粒子的初始速度为0
        main.startLifetime = 1000.0f;

        var pointCount = GazePoints.Count;
        ParticleSystem.Particle[] allParticles = new ParticleSystem.Particle[pointCount];
        main.maxParticles = pointCount;
        GetComponent<ParticleSystem>().Emit(pointCount);
        GetComponent<ParticleSystem>().GetParticles(allParticles);
        for (int i = 0; i < pointCount; i++)
        {
            allParticles[i].position = GazePoints_v3[i];    // 设置每个点的位置
            allParticles[i].startColor = Color.white;    // 设置每个点的rgb
            allParticles[i].startSize = 0.02f;

            Debug.Log(allParticles[i].position);

        }

        GetComponent<ParticleSystem>().SetParticles(allParticles, pointCount);      // 将点云载入粒子系统
    }

    void CreateMesh()
    {
        int num = GazePoints_v3.Count;

        GameObject pointObj = new GameObject();
        pointObj.name = "new";
        //处理大象朝向
        pointObj.transform.rotation = Quaternion.Euler(new Vector3(180, -180, 0));
        pointObj.AddComponent<MeshFilter>();
        pointObj.AddComponent<MeshRenderer>();
        Mesh meshNeed = new Mesh();
        Material mat = new Material(Shader.Find("Standard"));

        pointObj.GetComponent<MeshFilter>().mesh = meshNeed;
        pointObj.GetComponent<MeshRenderer>().material = mat;

        Vector3[] points = new Vector3[num];
        Color[] colors = new Color[num];
        int[] indecies = new int[num];
        for (int i = 0; i < num; ++i)
        {
            points[i] = GazePoints_v3[i];
            indecies[i] = i;
            colors[i] = Color.white;
        }

        meshNeed.vertices = points;
        meshNeed.colors = colors;
        meshNeed.SetIndices(indecies, MeshTopology.Points, 0);

    }

    public void Visualize()
    {
        foreach(var v3 in GazePoints_v3)
        {
            Instantiate(gazepoint, v3, Quaternion.identity);
        }
    }

    //public void PutToText()
    //{
    //    var IO = GetComponent<DataIO>();

    //    IO.WriteIntoTxt(GazePoints_v3);
    //}

    //private void GetFromText()
    //{
    //    var IO = GetComponent<DataIO>();
    //    var gazelist = IO.GetmytxtList();

    //    GazePoints_v3.Clear();

    //    for(int i = 0; i < gazelist.Count; i++)
    //    {
    //        gazelist[i] = gazelist[i].Replace("(", " ").Replace(")", " "); //将字符串中"("和")"替换为" "
    //        string[] s = gazelist[i].Split(',');
    //        GazePoints_v3.Add(new Vector3(float.Parse(s[0]), float.Parse(s[1]), float.Parse(s[2])));
    //    }
    //}


    /// <summary>
    /// 抓取整个屏幕截图
    /// </summary>
    /// <returns></returns>
    public Texture2D CaptureScreen()
    {
        //用屏幕的宽度和高度创建一个新的纹理
        Texture2D texture = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);

        StartCoroutine(CaptureScreenshot(texture));

        return texture;
    }

    IEnumerator CaptureScreenshot(Texture2D texture)
    {
        //只在每一帧渲染完成后才读取屏幕信息
        yield return new WaitForEndOfFrame();

        //读取屏幕像素信息并存储为纹理数据
        texture.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
        texture.Apply();// 这一句必须有，像素信息并没有保存在2D纹理贴图中
    }
#endif

}